package com.spark.colliery.module.agency.fragment

import android.annotation.SuppressLint
import android.content.DialogInterface
import android.os.Bundle
import android.support.v4.app.DialogFragment
import android.support.v7.widget.GridLayoutManager
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.EditorInfo
import com.blankj.utilcode.util.KeyboardUtils
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.spark.colliery.R
import com.spark.colliery.common.ext.watchWithClear
import com.spark.common.ext.hideIm
import com.spark.common.ext.windowOpacity
import com.spark.common.ext.wrapIO
import io.reactivex.Observable
import kotlinx.android.synthetic.main.frag_agency_search.*
import java.util.*
import java.util.concurrent.TimeUnit

/**
 * 待办右侧搜索
 */
class AgencySearchDialogFragment : DialogFragment() {
    private val historyList = ArrayList<String>()
    private val hotList = ArrayList<String>()

    companion object {
        fun newInstance(): AgencySearchDialogFragment {
            val args = Bundle()
            val fragment = AgencySearchDialogFragment()
            fragment.arguments = args
            return fragment
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setStyle(DialogFragment.STYLE_NO_TITLE, R.style.DialogFragmentAnimStyle)
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.frag_agency_search, container)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        dialog.window.setWindowAnimations(R.style.DialogFragmentAnimStyle)
        initData()
        initView()
        initLayout()
    }

    override fun onResume() {
        super.onResume()
        activity?.windowOpacity(0.6F)
    }

    private fun initView() {
        recy_agency_search_results.layoutManager = object : GridLayoutManager(context, 5) {
            override fun canScrollVertically(): Boolean {
                return false
            }
        }
        val historyAdapter = AgencySearchHintAdapter(R.layout.item_agencey_search)
        recy_agency_search_results.adapter = historyAdapter
        historyAdapter.addData(historyList)

        recy_agency_search_hot.layoutManager = object : GridLayoutManager(context, 4) {
            override fun canScrollVertically(): Boolean {
                return false
            }
        }
        val hotAdapter = AgencySearchHintAdapter(R.layout.item_agencey_search)
        recy_agency_search_hot.adapter = hotAdapter
        hotAdapter.addData(hotList)

        tv_cancel.setOnClickListener { doAction() }

        // image clear
        iv_clear.setOnClickListener {
            et_earch.setText("")
            tv_cancel.text = "取消"
        }

        et_earch.watchWithClear(iv_clear)

        et_earch.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
                if (!TextUtils.isEmpty(s)) {
                    tv_cancel.text = "搜索"
                } else {
                    recy_agency_search_history.visibility = View.GONE
                    ll_agency_search_hint.visibility = View.VISIBLE
                    tv_cancel.text = "取消"
                }
            }

            override fun afterTextChanged(s: Editable) {}
        })

        et_earch.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                search()
            }
            true
        }
    }


    private fun doAction() {
        KeyboardUtils.hideSoftInput(activity)
        val actionStr = tv_cancel.text
        if (actionStr == "搜索") {
            search()
        } else {
            dismiss()
        }
    }


    private fun initData() {
        historyList.add("铜川")
        historyList.add("煤矿")
        historyList.add("矿务局")
        historyList.add("安全")
        historyList.add("监察")

        hotList.add("日常办公")
        hotList.add("纠违处理")
        hotList.add("标化工作")
        hotList.add("标化检查")
    }

    /**
     * 初始化布局
     */
    private fun initLayout() {
        val screenWidth = resources.displayMetrics.widthPixels
        val screenHeight = resources.displayMetrics.heightPixels

        val lp = dialog.window.attributes
        lp.width = (screenWidth * 0.75).toInt()
        lp.height = screenHeight
        lp.gravity = Gravity.RIGHT
        dialog.window.attributes = lp
    }

    override fun onDismiss(dialog: DialogInterface?) {
        super.onDismiss(dialog)
        activity?.apply {
            windowOpacity(1.0F)
            hideIm()
        }
    }

    @SuppressLint("CheckResult")
    private fun search() {
        Observable
                .empty<Any>()
                .delay(1, TimeUnit.SECONDS)
                .wrapIO()
                .subscribe(
                        {
                            recy_agency_search_results.visibility = View.VISIBLE
                            ll_agency_search_hint.visibility = View.GONE


                        },
                        {},
                        {},
                        {}
                )
    }

}

class AgencySearchHintAdapter(layoutRes: Int) : BaseQuickAdapter<String, BaseViewHolder>(layoutRes) {
    override fun convert(helper: BaseViewHolder?, item: String?) {
        if (item == null) return
        helper?.apply {
            setText(R.id.tv_seach, item)
        }
    }

}
